// 滚动锚点
<template>
  <div class="rolling-anchor">
    <div
      v-for="(item, index) in anchorList"
      :key="index"
      @click="rollToAnchor(item, index)"
      class="anchor-item pointer"
      :class="index === activeIndex ? 'isActiveItem' : ''"
    >
      {{ index + 1 }}
    </div>
  </div>
</template>

<script>
export default {
  props: {
    //   接收的滚动锚点数组 这里接收的是父组件传来的ref
    anchorList: {
      type: Array,
      default: () => [],
    },
  },

  mounted() {
    this.$parent.$el.addEventListener("scroll", this.onScroll, false);
  },

  beforeDestroy() {
    this.$parent.$el.removeEventListener("scroll", this.onScroll);
  },

  data() {
    return {
      activeIndex: 0,
    };
  },

  methods: {
    rollToAnchor(anchorRef) {
      this.$parent.$refs[`${anchorRef}`].$el.scrollIntoView({
        behavior: "smooth", // 平滑过渡
        block: "start", // 上边框与视窗顶部平齐。默认值
        inline: "start",
      });
    },
    // 滚动监听器
    onScroll() {
      if (this.anchorList.length === 0) {
        return;
      }
      // 获取所有锚点元素
      const navContents = [];
      this.anchorList.forEach((i) => {
        navContents.push(this.$parent.$refs[`${i}`].$el);
      });
      // 所有锚点元素的 offsetTop
      const offsetTopArr = [];
      navContents.forEach((item) => {
        offsetTopArr.push(item.offsetTop);
      });
      // 获取当前文档流的 scrollTop
      const scrollTop =
        this.$parent.$el.scrollTop ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;

      // 定义当前点亮的导航下标
      let navIndex = 0;
      for (let n = 0; n < offsetTopArr.length; n++) {
        // 如果 scrollTop 大于等于第n个元素的 offsetTop 则说明 n-1 的内容已经完全不可见
        // 那么此时导航索引就应该是n了
        if (scrollTop >= offsetTopArr[n]) {
          navIndex = n;
        }
      }
      this.activeIndex = navIndex;
    },
  },
};
</script>

<style lang="scss">
.rolling-anchor {
  position: fixed;
  //   之下的样式可以随意更改
  right: 40px;
  top: 200px;
  z-index: 100;
  display: flex;
  flex-direction: column;
  row-gap: 20px;
  .anchor-item {
    width: 32px;
    height: 32px;
    background-color: #ffffff;
    border-radius: 50%;
    border: 1px #cccdd3 solid;
    display: flex;
    align-items: center;
    justify-content: center;
    &:hover {
      color: #ff6a00;
      border: 1px solid #ff6a00;
      background: #fff0e6;
    }
  }
  .isActiveItem {
    color: #ff6a00;
    border: 1px solid #ff6a00;
    background: #fff0e6;
  }
}
</style>
